<template>
  <div class="app-container" v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <el-divider content-position="left">企业信息</el-divider>
      <el-form-item label="营业执照" prop="businessLicensePath">
        <ImageUpload @input="handleBusinessLicense" :limit="1" v-model="form.businessLicensePath"></ImageUpload>
      </el-form-item>

      <el-form-item label="企业名称" prop="companyName">
        <el-input v-model="form.companyName" placeholder="请输入企业名称" />
      </el-form-item>

      <el-form-item label="统一社会信用代码" prop="creditCode">
        <el-input v-model="form.creditCode" :disabled="form.signStatus === 2" placeholder="请输入统一社会信用代码" />
      </el-form-item>

      <el-form-item label="公司邮箱" prop="companyEmail">
        <el-input v-model="form.companyEmail" placeholder="请输入公司邮箱" />
      </el-form-item>

      <el-form-item label="营业执照有效期" required>
        <el-col :span="11">
          <el-form-item prop="licenseValidFrom">
            <el-date-picker clearable v-model="form.licenseValidFrom" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期起始" />
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="licenseValidTo">
            <el-date-picker clearable v-model="form.licenseValidTo" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期结束" />
          </el-form-item>
        </el-col>
      </el-form-item>


      <el-form-item label="经营地址" prop="operateAddress">
        <el-input v-model="form.operateAddress" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" placeholder="请输入经营地址" />
      </el-form-item>


      <el-form-item label="业务简介" prop="companyProfile">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 12}" v-model="form.companyProfile" placeholder="请输入业务简介" />
      </el-form-item>

      <el-form-item label="公司内部照" prop="storefrontPhotoPath">
        <ImageUpload :limit="5" v-model="form.storefrontPhotoPath"></ImageUpload>
      </el-form-item>


      <el-divider content-position="left">法人信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="身份证正面" prop="legalRepresentativeIdFront">
            <ImageUpload :limit="1" @input="handleLegalRepresentativeFront" v-model="form.legalRepresentativeIdFront"></ImageUpload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证背面" prop="legalRepresentativeIdBack">
            <ImageUpload @input="handleLegalRepresentativeBack" :limit="1" v-model="form.legalRepresentativeIdBack"></ImageUpload>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="12">
          <el-form-item label="法人姓名" prop="legalRepresentativeName">
            <el-input v-model="form.legalRepresentativeName" placeholder="请输入法人姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">

          <el-form-item label="法人手机" prop="legalRepresentativePhone">
            <el-input v-model="form.legalRepresentativePhone" placeholder="请输入法人手机" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="法人身份证号" prop="legalRepresentativeIdCard">
        <el-input v-model="form.legalRepresentativeIdCard" placeholder="请输入法人身份证号" />
      </el-form-item>

      <el-form-item label="身份证有效期" required>
          <el-col :span="11">
            <el-form-item prop="legalIdNumberBeginTime">
              <el-date-picker clearable v-model="form.legalIdNumberBeginTime" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期起始" />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="legalIdNumberEndTime">
            <el-date-picker clearable v-model="form.legalIdNumberEndTime" type="date" value-format="yyyy-MM-dd" format="yyyy 年 MM 月 dd 日" placeholder="请选择有效期起始" />
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="法人身份证地址" prop="legalRepresentativeAddress">
        <el-input v-model="form.legalRepresentativeAddress" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" placeholder="请输入法人身份证地址" />
      </el-form-item>

      <el-divider content-position="left">贴牌</el-divider>
      <el-form-item label="平台logo" prop="extend">
        <ImageUpload :limit="1" v-model="extend.logo"></ImageUpload>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="平台名称" prop="extend">
            <el-input v-model="extend.loginName" placeholder="请输入平台名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="域名" prop="extend">
            <el-input v-model="extend.domainName" placeholder="请输入域名" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">管理员</el-divider>
       <el-row>
        <el-col :span="12">
          <el-form-item label="管理员姓名" prop="administratorName">
            <el-input v-model="form.administratorName" placeholder="请输入管理员姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="管理员手机号" prop="administratorPhone">
            <el-input v-model="form.administratorPhone" autocomplete="new-password" placeholder="请输入管理员手机号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left">费率</el-divider>
      <el-form-item label="费率/%" prop="extend">
        <el-input-number v-model="extend.rate" :min="0" :max="100" :precision="2" placeholder="请输入费率/%"></el-input-number>
      </el-form-item>


    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">提 交</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </div>
</template>
<script>

import {businessLicense, idCard} from "@/api/common";
import { getPlatform, addPlatform, updatePlatform } from "@/api/system/platform"

export default {
  name: "platformOperate",
  props:{
    organizationId:{
     type:String,
    },
  },
  data() {
    return{
      loading:false,
      form:{
        organizationId:null,
        organizationType: null,
        companyName: null,
        operateAddress: null,
        companyProfile: null,
        creditCode: null,
        companyEmail:null,
        licenseValidFrom: null,
        licenseValidTo: null,
        businessLicensePath: null,
        storefrontPhotoPath: null,
        legalRepresentativeName: null,
        legalRepresentativeIdCard: null,
        legalRepresentativeIdFront: null,
        legalRepresentativeIdBack: null,
        legalRepresentativePhone: null,
        legalRepresentativeAddress:null,
        legalIdNumberBeginTime :null,
        legalIdNumberEndTime:null,
        administratorName: null,
        administratorPhone: null,
        signStatus: null,
        extend:null,
      },
      extend: {
        rate:0,
        logo:null,
        domainName:null,
        loginName:null
      },
      // 表单校验
      rules: {
        organizationType: [
          { required: true, message: "组织类型 不能为空", trigger: "change" }
        ],
        companyName: [
          { required: true, message: "平台运营商名称不能为空", trigger: "blur" }
        ],
        registeredAddress: [
          { required: true, message: "注册地址不能为空", trigger: "blur" }
        ],
        creditCode: [
          { required: true, message: "统一社会信用代码不能为空", trigger: "blur" }
        ],
        licenseValidFrom: [
          { required: true, message: "有效期起始不能为空", trigger: "blur" }
        ],
        licenseValidTo: [
          { required: true, message: "有效期起始不能为空", trigger: "blur" }
        ],
        companyEmail: [
          { required: true, message: "有效期起始不能为空", trigger: "blur" },
          {  type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        operateAddress: [
          { required: true, message: "经营地址不能为空", trigger: "blur" }
        ],
        legalRepresentativeName: [
          { required: true, message: "法人姓名不能为空", trigger: "blur" }
        ],
        legalRepresentativeIdCard: [
          { required: true, message: "法人身份证号不能为空", trigger: "blur" }
        ],

        legalRepresentativeAddress: [
          { required: true, message: "法人身份证地址不能为空", trigger: "blur" }
        ],
        legalRepresentativePhone: [
          { required: true, message: "法人手机不能为空", trigger: "blur" }
        ],
        administratorName: [
          { required: true, message: "管理员姓名不能为空", trigger: "blur" }
        ],
        administratorPhone: [
          { required: true, message: "管理员手机号不能为空", trigger: "blur" }
        ],
        legalIdNumberBeginTime: [
          { required: true, message: "身份证生效日期为空", trigger: "blur" }
        ],
        legalIdNumberEndTime: [
          { required: true, message: "身份证失效日期为空", trigger: "blur" }
        ],
        legalRepresentativeIdBack: [
          { required: true, message: "请上传身份证背面", trigger: ["blur","change"] }
        ],
        legalRepresentativeIdFront: [
          { required: true, message: "请上传身份证正面", trigger: ["blur","change"] }
        ],
        businessLicensePath: [
          { required: true, message: "请上传营业执照", trigger: ["blur","change"] }
        ],
      }
    }
  },
  mounted() {

  },
  methods:{
    handleBusinessLicense(obj){
      if(obj){
        this.loading = true
        businessLicense({url:obj}).then(res=>{
          this.loading = false
          let data = res.data
          if (data && data.words_result_num>0){
            let words_result = data.words_result
            this.form.companyName = words_result['单位名称'].words
            this.form.operateAddress = words_result['地址'].words
            this.form.licenseValidFrom = this.arseDate(words_result['成立日期'].words,/(\d{4})年(\d{1,2})月(\d{1,2})日/)
            this.form.licenseValidTo = this.arseDate("2999年12月31日",/(\d{4})年(\d{1,2})月(\d{1,2})日/)
            if (this.form.signStatus !== 2){
              this.form.creditCode = words_result['社会信用代码'].words
            }
            this.form.legalRepresentativeName = words_result['法人'].words
          }
        }).catch(()=>{
          this.loading = false
        })
      }
    },
    handleLegalRepresentativeFront(obj){
      if(obj){
        this.loading = true
        idCard({url:obj,idCardSide:"front"}).then(res=>{
          this.loading = false
          let data = res.data
          if (data && data.words_result_num>0){
            let words_result = data.words_result
            this.form.legalRepresentativeName = words_result['姓名'].words
            this.form.legalRepresentativeAddress = words_result['住址'].words
            this.form.legalRepresentativeIdCard = words_result['公民身份号码'].words
          }
        }).catch(()=>{
          this.loading = false
        })
      }
    },
    handleLegalRepresentativeBack(obj){
      if(obj){
        this.loading = true
        idCard({url:obj,idCardSide:"back"}).then(res=>{
          this.loading = false
          let data = res.data
          if (data && data.words_result_num>0){
            let words_result = data.words_result
            this.form.legalIdNumberBeginTime = this.arseDate(words_result['签发日期'].words,/(\d{4})(\d{1,2})(\d{1,2})/)
            if (words_result['失效日期'].words === "长期"){
              this.form.legalIdNumberEndTime = this.arseDate("29991231",/(\d{4})(\d{1,2})(\d{1,2})/)
            }else{
              this.form.legalIdNumberEndTime = this.arseDate(words_result['失效日期'].words,/(\d{4})(\d{1,2})(\d{1,2})/)
            }
          }
        }).catch(()=>{
          this.loading = false
        })
      }
    },

    getDetail(){
      this.loading = true
      getPlatform(this.organizationId).then(res=>{
        this.loading = false
        this.form = res.data
        if (this.form.extend){
          this.extend = JSON.parse(this.form.extend)
        }
      }).catch(()=>{
        this.loading = false
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.extend = Object.keys(this.extend || {})
            .filter(key => ['logo', 'domainName', 'loginName',"rate"].includes(key))
            .reduce((obj, key) => {
              obj[key] = this.extend[key];
              return obj;
            }, {});

          if (Object.keys(this.form.extend).length > 0) {
            this.form.extend = JSON.stringify(this.form.extend);
          }
          this.loading = true
          if (this.form.organizationId != null) {
            updatePlatform(this.form).then(response => {
              this.loading = false
              this.$modal.msgSuccess("修改成功")
              this.handleCancel(true)
            }).catch(()=>{
              this.loading = false
            })
          } else {
            addPlatform(this.form).then(response => {
              this.loading = false
              this.$modal.msgSuccess("新增成功")
              this.handleCancel(true)
            }).catch(()=>{
              this.loading = false
            })
          }
        }
      })
    },

    handleCancel(val){
      this.$emit("cancel",val)
    },

    arseDate(dateStr,regex) {
      const match = dateStr.match(regex);

      if (!match) return null;

      const year = parseInt(match[1]);
      // 注意：Date 对象的月份是 0-11，需要减 1
      const month = parseInt(match[2]) - 1;
      const day = parseInt(match[3]);

      return new Date(year, month, day);
    }
  },
  watch:{
    organizationId:{
      handler(val){
        if (val){
          this.getDetail()
        }
      },
      immediate:true
    }
  }
}
</script>
<style scoped lang="scss">
  ::v-deep .el-col{
    .el-form-item{
      width: 100%;
      .el-date-editor{
        width: 100%;
      }
    }
  }
  .line{
    text-align: center;
  }


</style>
